//
//  FMDBManager.m
//  FMDB
//
//  Created by mHome on 2017/1/16.
//  Copyright © 2017年 mHome. All rights reserved.
//

#import "FMDBManager.h"
#import "FMDatabase.h"

@implementation FMDBManager
{
    FMDatabase *fmdb;

}
+(FMDBManager *) shareManager
{
    static FMDBManager *db = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        if (db == nil) {
            db = [[FMDBManager alloc]init];
            
        }
    });
    return db;
}

-(id) init
{
    self = [super init];
    if (self) {
        //获取数据库文件路径
        NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *fileName = [doc stringByAppendingPathComponent:@"app.sqlite"];
        fmdb = [[FMDatabase alloc]initWithPath:fileName];
        if ([fmdb open]) {
            NSLog(@"============成功");
            [self creatList];
        }else{
            NSLog(@"------------失败");
        }
        
    }
    return self;
}
-(void) creatList
{
    BOOL result = [fmdb executeUpdate:@"create table if not exists app(id varchar ,CLASS_SHORT_NAME TEXT ,sex TEXT ,tel TEXT)"];
    if (result) {
        NSLog(@"==========创建表成功");
    }else{
        NSLog(@"----------失败");
    }
}

-(BOOL) insterDataWithModel :(FMDBModel *) model :(NSArray *)modelArray
{
    BOOL isSucess = [fmdb executeUpdate:@"insert into app(id , CLASS_SHORT_NAME , sex , tel) values(?,?,?,?)",@(model.id),model.CLASS_SHORT_NAME,model.SCD_DATE,model.tel];
    if (isSucess) {
        NSLog(@"===========插入数据成功");
    }else{
        NSLog(@"-----------失败");
    }
    return isSucess;
}


//返回查询结果
-(FMResultSet *) backResults : (NSString *) conditions
{
    NSString *querySql = [NSString stringWithFormat:@"select * from %@",conditions];
    return  [fmdb executeQuery:querySql];
}
-(NSArray *) backResultsArray : (NSArray *) conditionsArray
{
    return conditionsArray;
}
-(BOOL) deleteData
{
    NSString *deleteSql = [NSString stringWithFormat:@"delete from %@",@"app"];
    BOOL result = [fmdb executeUpdate:deleteSql];
    if (result) {
        NSLog(@"--------删除表");
    }else{
        NSLog(@"========失败");
    }
    return result;
}
- (NSMutableArray *)dataArray {
    
    //执行查询语句，得到查询结果
    FMResultSet *set = [fmdb executeQuery:@"select * from app"];
    //上述方法就是将数据去全部获取放进集合
    NSMutableArray *array = [NSMutableArray array];
    while ([set next]) {
        FMDBModel *dog = [[FMDBModel alloc]init];
        dog.CLASS_SHORT_NAME = [set stringForColumn:@"CLASS_SHORT_NAME"];
        dog.SCD_DATE = [set stringForColumn:@"sex"];
        
        [array addObject:dog];
        NSLog(@"dag=%@ %@",dog.CLASS_SHORT_NAME,dog.SCD_DATE);
        
    }
    return array;
}


@end
